package com.lw.leetcode.binary.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * sort
 * binary
 * 2070. 每一个查询的最大美丽值
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/27 21:06
 */
public class MaximumBeauty {

    private int[][] items;
    private int length;
    private int f;
    private int e;

    public int[] maximumBeauty(int[][] items, int[] queries) {
        Arrays.sort(items, (a, b) -> a[0] == b[0] ? Integer.compare(b[1], a[1]) : Integer.compare(a[0], b[0]));
        this.items = items;
        this.length = items.length;
        this.f = items[0][0];
        this.e = items[length - 1][0];
        int v = items[0][1];
        for (int[] item : items) {
            item[1] = Math.max(item[1], v);
            v = item[1];
        }
        int len = queries.length;
        int[] arr = new int[len];
        for (int i = 0; i < len; i++) {
            arr[i] = find(queries[i]);
        }
        return arr;
    }

    private int find(int value) {
        if (value < f) {
            return 0;
        }
        if (value == f) {
            return items[0][1];
        }
        if (value >= e) {
            return items[length - 1][1];
        }
        int st = 0;
        int end = items.length;
        while (st < end) {
            int m = st + ((end - st + 1) >> 1);
            if (items[m][0] < value) {
                st = m;
            } else {
                end = m - 1;
            }
        }
        if (items[st + 1][0] == value) {
            return items[st + 1][1];
        }
        return items[st][1];
    }


}
